package com.daniel.memo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.daniel.database.Database;

public class EditTaskViewActivity extends Activity{

	private TextView completedStatus;
	
	private EditText titleEdtTxt;
	
	private Button notiBtn;
	private Button dateBtn;
	private Button timeBtn;
	private Button priorityBtn;
	
	private EditText memoEdtTxt;
	
	private boolean isNotiOn;
	private int priority;
	
	private boolean isCompleted;
	
	private int year, month, day;
	private int hourOfDay, minute;
	private boolean is24HourView = false;
	
	public static final int DATE_PICKER_DIALOG = 0;
	public static final int TIME_PICKER_DIALOG = 1;
	
	public static final String DATE_FORMAT = "yyyy-MM-dd";
	public static final String TIME_FORMAT = "h:mm a";

	private Calendar notiDateTime;
	
	private int memoId;
	private int taskRowId;
	private int todoRowId;
	
	private Database db;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.task_edit_activity);
    
        db = new Database(this);
        
        notiDateTime = Calendar.getInstance();
        
        connectInput();
        
        Bundle extras = getIntent().getExtras();   
        if (extras != null) {
        	taskRowId = extras.getInt(Task.TASK_ID);
        	todoRowId = extras.getInt(Todo.TODO_ID);
        	        	
        	if (taskRowId == -1) {//create new task
            	isNotiOn = false;
            	priority = Task.MEDIUM;
            	isCompleted = false;			
				
                year = notiDateTime.get(Calendar.YEAR);
                month = notiDateTime.get(Calendar.MONTH);
                day =  notiDateTime.get(Calendar.DAY_OF_MONTH);
                
                hourOfDay = notiDateTime.get(Calendar.HOUR_OF_DAY);
                minute = notiDateTime.get(Calendar.MINUTE);
                
        	} else {// edit existing task
        		populateData(taskRowId);
        		
                year = notiDateTime.get(Calendar.YEAR);
                month = notiDateTime.get(Calendar.MONTH);
                day =  notiDateTime.get(Calendar.DAY_OF_MONTH);
                
                hourOfDay = notiDateTime.get(Calendar.HOUR_OF_DAY);
                minute = notiDateTime.get(Calendar.MINUTE);
                
//              Log.d("NotiDateTime","" + year + "-" + month + "-" + day + " " + hourOfDay + "-" + minute);
                
        	}
        }
    }

    
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.edit_task_menu, menu);
    	return true;
    }
    
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch(item.getItemId()) {
    		case R.id.task_menu_save_id:
    			if (taskRowId == -1) {
    				extractTaskDataAndSave();
    				
    			} else {
    				extractTaskDataAndUpdate();
    				
    			}
    			
				finish();
    			return true;
    			
    		case R.id.task_menu_cancel_id:
    			finish();
    			return true;
    			
    		default:
    			return super.onOptionsItemSelected(item);
    	}
    }
    
    @Override
    public void onStart() {
    	super.onStart();
    	db.open();
    }

    @Override
    public void onStop() {
    	super.onStop();
    	db.close();
    }
    
    public void setStringOnDateTimeOnButtons() {
    	Date date = notiDateTime.getTime();
    	
    	SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
    	String strDate = dateFormat.format(date);
    	dateBtn.setText(strDate);
    	
    	SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
    	String strTime = timeFormat.format(date);
    	timeBtn.setText(strTime);
    }
    
    public void populateData(int taskId)  {
		db.open();
		
		Cursor cursor = db.fetchTasksByTaskId(taskId);
		cursor.moveToFirst();
		memoId = cursor.getInt(1);
		String notiDate = cursor.getString(3);
		int isNotiOn = cursor.getInt(4);
		int priority = cursor.getInt(5);
		int isCompleted = cursor.getInt(6);
		todoRowId = cursor.getInt(7);
		
		this.isNotiOn = isNotiOn != 0;
		this.priority = priority;
		this.isCompleted = isCompleted != 0;
		
		Cursor memoCursor = db.fetchMemoById(memoId);
		memoCursor.moveToFirst();
		String title = memoCursor.getString(0);
		String memo = memoCursor.getString(2);
		
		SimpleDateFormat sdf = new SimpleDateFormat(Task.TASK_DATE_TIME_FORMAT);
		try {
			notiDateTime.setTime(sdf.parse(notiDate));
			
		} catch (ParseException e) {
			Log.d("EditTaskViewActivity - populateData()", e.toString());
			e.printStackTrace();
			
		}
		
		setStringOnDateTimeOnButtons();
    	
		if (isCompleted != 0) {
			completedStatus.setText(R.string.taskCompleted);
		} else {
			completedStatus.setText(R.string.taskNotCompleted);
		}
		
		if (this.isNotiOn) {
			notiBtn.setText(R.string.notification_on);
			dateBtn.setVisibility(View.VISIBLE);
			timeBtn.setVisibility(View.VISIBLE);

		} else {
			notiBtn.setText(R.string.notification_off);
			dateBtn.setVisibility(View.GONE);
			timeBtn.setVisibility(View.GONE);
			
		}
		
		titleEdtTxt.setText(title);
		memoEdtTxt.setText(memo);

		db.close();
    }

    public void connectInput() {
    	completedStatus = (TextView) findViewById(R.id.completed_status_txt_id);

    	titleEdtTxt = (EditText) findViewById(R.id.task_title_edt_id);
    	memoEdtTxt = (EditText) findViewById(R.id.task_memo_edit_txt_id);
    	
    	notiBtn = (Button) findViewById(R.id.task_notification_btn);

    	notiBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String notiStatus = notiBtn.getText().toString();
				if (getResources().getString(R.string.notification_on).equals(notiStatus)) {
					notiBtn.setText(getResources().getString(R.string.notification_off));
					isNotiOn = false;
					dateBtn.setVisibility(View.GONE);
					timeBtn.setVisibility(View.GONE);
					
				} else {
					notiBtn.setText(getResources().getString(R.string.notification_on));
					isNotiOn = true;
					dateBtn.setVisibility(View.VISIBLE);
					timeBtn.setVisibility(View.VISIBLE);
					
				}
			}
		});

    	dateBtn = (Button) findViewById(R.id.task_date_btn);
    	dateBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DATE_PICKER_DIALOG);
			}
		});

    	timeBtn = (Button) findViewById(R.id.task_time_btn);
    	timeBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(TIME_PICKER_DIALOG);
			}
		});
    	
    	setStringOnDateTimeOnButtons();
    	
    	priorityBtn = (Button) findViewById(R.id.priority_btn_id);
    	priorityBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String priorityStatus = priorityBtn.getText().toString();
				if (getResources().getString(R.string.high).equals(priorityStatus)) {
					priorityBtn.setText(getResources().getString(R.string.medium));
					priority = Task.MEDIUM;
					
				} else if (getResources().getString(R.string.medium).equals(priorityStatus)){
					priorityBtn.setText(getResources().getString(R.string.low));
					priority = Task.LOW;
					
				} else if (getResources().getString(R.string.low).equals(priorityStatus)){
					priorityBtn.setText(getResources().getString(R.string.high));
					priority = Task.HIGH;
					
				}
			}
		});
    	
    }//end of connectInput()
	
    public void extractTaskDataAndUpdate() {
    	String taskTitle = titleEdtTxt.getText().toString();
    	boolean taskNoti = this.isNotiOn;
    	String date = dateBtn.getText().toString();
    	String time = timeBtn.getText().toString();
    	int taskPriority = this.priority;
    	String taskMemo = memoEdtTxt.getText().toString();
    	
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        String currentDate = dateFormat.format(cal.getTime());
    	
    	db.updateTask(memoId, taskRowId, taskTitle, taskMemo, currentDate, todoRowId, date + " " + time, taskNoti, taskPriority, isCompleted);
    }
    
    public void extractTaskDataAndSave() {
    	String taskTitle = titleEdtTxt.getText().toString();
    	boolean taskNoti = this.isNotiOn;
    	String taskMemo = memoEdtTxt.getText().toString();
    	
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        String currentDate = dateFormat.format(cal.getTime());
        
        String strNotiDate;
        if (taskNoti == true) {
	        notiDateTime.set(year, month, day, hourOfDay, minute);
	        SimpleDateFormat notiTimeDateFormat = new SimpleDateFormat(Task.TASK_DATE_TIME_FORMAT);
	        strNotiDate = notiTimeDateFormat.format(notiDateTime.getTime());
        } else {
        	strNotiDate = "";
        }
        
        taskRowId = (int) db.insertTask(taskTitle, taskMemo, currentDate, todoRowId, strNotiDate, this.isNotiOn, this.priority, isCompleted);
    }
    
    @Override
    protected Dialog onCreateDialog (int id) {
    	switch (id) {
    		case DATE_PICKER_DIALOG:
    			return new DatePickerDialog (this, datePickerListener, year, month, day);
    			
    		case TIME_PICKER_DIALOG:
    			return new TimePickerDialog(this, timePickerListener, hourOfDay, minute, is24HourView);
    			
    	}
    	return null;
    }

    private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			
			setYear(year);
			setMonth(monthOfYear);
			setDay(dayOfMonth);
			
			Calendar cDate = Calendar.getInstance();
			cDate.set(year, monthOfYear, dayOfMonth);
			Date date = cDate.getTime();
	    	SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
	    	String strDate = dateFormat.format(date);
			Log.d("Date", strDate);
			
			dateBtn.setText(strDate);
		}
	};

	private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			
			setHour(hourOfDay);
			setMinute(minute);
			
			Calendar cTime = Calendar.getInstance();
			cTime.set(0, 0, 0, hourOfDay, minute);
			Date date = cTime.getTime();
	    	SimpleDateFormat dateFormat = new SimpleDateFormat(TIME_FORMAT);
	    	String strTime = dateFormat.format(date);
	    	Log.d("Time", strTime);
	    	
	    	timeBtn.setText(strTime);
		}
	};
	
	public void setYear(int year) {
		this.year = year;
	}
	public void setMonth(int monthOfYear) {
		this.month = monthOfYear;
	}
	public void setDay(int dayOfMonth) {
		this.day = dayOfMonth;
	}
	
	public void setHour(int hour) {
		this.hourOfDay = hour;
	}
	public void setMinute(int minute) {
		this.minute = minute;
	}
	
}
